<?php


namespace app\service;


use app\model\Brand as BrandModel;
use app\model\Category as CategoryModel;
use app\model\Goods as GoodsModel;
use app\model\Shop as ShopModel;
use app\model\TaobaoGoods as TaobaoGoodsModel;
use app\model\TaobaoGoodsArchive as TaobaoGoodsArchiveModel;
use think\App;
use think\facade\Cache;

class DtkService
{
    private $goodsModel;
    private $goodsService;
    private $tbGoodsModel;
    private $tbGoodsArchiveModel;
    private $categoryModel;
    private $brandModel;
    private $shopModel;
    private $appKey;
    private $appSecret;

    public function __construct(App $app)
    {
        $this->goodsModel = app()->make(GoodsModel::class);
        $this->tbGoodsModel = app()->make(TaobaoGoodsModel::class);
        $this->tbGoodsArchiveModel = app()->make(TaobaoGoodsArchiveModel::class);
        $this->categoryModel = app()->make(CategoryModel::class);
        $this->brandModel = app()->make(BrandModel::class);
        $this->shopModel = app()->make(ShopModel::class);
        $this->goodsService = app()->make(GoodsService::class);
        $this->appKey = app()->make(SettingService::class)->getOneSetting('dtkAppKey');

        $this->appSecret = app()->make(SettingService::class)->getOneSetting('dtkAppSecret');
    }

    public function getGoodsList()
    {
        set_time_limit(0);
        $client = new \GetGoodsList();
        $client->setAppKey($this->appKey);
        $client->setAppSecret($this->appSecret);
        $client->setVersion('v1.2.4');
        //参数
        $params = array();
        $params['pageSize'] = 100;
        $params['pageId'] = 1;
        $addTotal = 0;
        $updateTotal = 0;
        $categories = $this->categoryModel->select();
        foreach ($categories as $key => $item) {
            $params['cids'] = $item['id'];
            $result = $client->setParams($params)->request();
            $resultData = json_decode($result, true);
            // 、、print_r($resultData);exit();
            if (!is_null($resultData['data']) && !empty($resultData['data'])) {
                foreach ($resultData['data']['list'] as $key => $item) {
                    // print_r($item);exit;
                    $data = $this->convertGoods($item);
                    $data['preview_start_time'] = $item['previewStartTime'];
                    $this->saveBrand($item['brandName'], $item['brandId']);
                    $this->saveShop($item['shopName'], $item['sellerId'], $item['shopType'], $item['shopLogo'], $item['shipScore'], $item['serviceScore'], $item['dsrScore']);
                    $goodsData = $this->goodsModel->where('goods_id', $item['goodsId'])->find();
                    if (!empty($goodsData)) {
                        $this->goodsModel->where('goods_id', $item['goodsId'])->save($data);
                        $updateTotal++;
                        continue;
                    }
                    $addTotal++;
                    $this->goodsModel->insert($data);
                }
            }
        }
        return array('addTotal' => $addTotal, 'updateTotal' => $updateTotal);
    }

    /**
     * 大淘客搜索
     *
     * @param $params
     * @return array
     */
    public function search($params)
    {
        $client = new \GetDtkSearchGoods();
        $client->setAppKey($this->appKey);
        $client->setAppSecret($this->appSecret);
        $client->setVersion('v2.1.2');
        $result = $client->setParams($params)->request();
        $resultData = json_decode($result, true);
        if (is_null($resultData['data']) || empty($resultData['data'])) {
            return null;
        }
        $list = array();
        $maxPage = 1;
        foreach ($resultData['data']['list'] as $key => $item) {
            $item = $this->convertGoods($item);
            $item['sales'] = $this->goodsService->handleSales($item['month_sales']);
            $list[] = $item;
        }
        if (empty($list)) {
            return null;
        }
        if ($resultData['data']['totalNum'] > $params['pageSize']) {
            $maxPage = ceil($resultData['data']['totalNum'] / $params['pageSize']);
        }
        $data['list'] = $list;
        $data['maxPage'] = $maxPage;
        return $data;
    }

    /**
     * 获取商品详情
     *
     * @param $dtkGoodsId
     * @return array|null
     */
    public function getGoodsDetail($dtkGoodsId)
    {
        $client = new \GetGoodsDetails();
        $client->setAppKey($this->appKey);
        $client->setAppSecret($this->appSecret);
        $client->setVersion('v1.2.3');
        $params = array('id' => $dtkGoodsId);
        $result = $client->setParams($params)->request();
        $resultData = json_decode($result, true);
        if (is_null($resultData['data']) || empty($resultData['data'])) {
            return null;
        }
        $item = $resultData['data'];
        $data = $this->convertGoods($item);
        $data['preview_start_time'] = $item['previewStartTime'];
        $this->saveBrand($item['brandName'], $item['brandId']);
        $this->saveShop($item['shopName'], $item['sellerId'], $item['shopType'], $item['shopLogo'], $item['shipScore'], $item['serviceScore'], $item['dsrScore']);
        $goodsData = $this->goodsModel->where('goods_id', $item['goodsId'])->find();
        if (!empty($goodsData)) {
            $this->goodsModel->where('goods_id', $item['goodsId'])->save($data);
        } else {
            $this->goodsModel->insert($data);
        }
        $data['sales'] = $this->goodsService->handleSales($data['month_sales']);
        $data['special_text'] = isset($data['special_text']) ? explode(',', $data['special_text']) : array();
        return $data;
    }

    /**
     * 获取热搜关键字
     *
     * @return array|false|mixed|string[]
     */
    public function getSearchKeywords()
    {
        $hotKeywords = Cache::get('hotKeywords');
        if (!empty($hotKeywords)) {
            $hotKeywords = explode(',', $hotKeywords);
            shuffle($hotKeywords);
            return $hotKeywords;
        }
        $client = new \GetTop100();
        $client->setAppKey($this->appKey);
        $client->setAppSecret($this->appSecret);
        $client->setVersion('v1.0.1');
        // 1：买家热搜榜（默认）、2：淘客热搜榜
        $params = array('type' => 1);
        $result = $client->setParams($params)->request();
        //print_r($result);exit;
        $resultData = json_decode($result, true);
        if (!isset($resultData['data']) || empty($resultData['data'])) {
            return array();
        }
        Cache::set('hotKeywords', implode(',', $resultData['data']['hotWords']), 3600);
        return $resultData['data']['hotWords'];
    }

    /**
     * 高效转链
     *
     * @param $goodsId
     * @return array
     */
    public function getPrivilegeLink($goodsId) : array
    {
        $params = array('goodsId' => $goodsId);
        $client = new \GetPrivilegeLink();
        $client->setAppKey($this->appKey);
        $client->setAppSecret($this->appSecret);
        $client->setVersion('v1.3.1');
        $result = $client->setParams($params)->request();
        $resultData = json_decode($result, true);
        //print_r($resultData);exit();
        if (is_null($resultData['data']) || empty($resultData['data'])) {
            return array();
        }
        $linkData = $resultData['data'];
        $data['coupon_click_url'] = $linkData['couponClickUrl'];
        $data['tkl'] = $linkData['tpwd'];
        $data['long_tkl'] = $linkData['longTpwd'];
        $data['item_url'] = $linkData['itemUrl'];
        $data['short_link'] = $linkData['shortUrl'];
        $data['coupon_info'] = $linkData['couponInfo'];
        $data['actual_price'] = $linkData['actualPrice'];
        $data['original_price'] = $linkData['originalPrice'];
        return $data;
    }

    /**
     * 转换商品
     *
     * @param $item
     * @return array
     */
    private function convertGoods($item): array
    {
        $data['dtk_goods_id'] = $item['id'];
        $data['goods_id'] = $item['goodsId'];
        $data['title'] = $item['title'];
        $data['pic'] = $item['mainPic'];
        $data['pics'] = json_encode(array($item['marketingMainPic']));
        $data['short_title'] = $item['dtitle'];
        $data['original_price'] = $item['originalPrice'];
        $data['actual_price'] = $item['actualPrice'];
        $data['discounts'] = $item['discounts'];
        $data['commission_type'] = $item['commissionType'];
        $data['commission_rate'] = $item['commissionRate'];
        $data['coupon_link'] = $item['couponLink'];
        $data['coupon_total_num'] = $item['couponTotalNum'];
        $data['coupon_receive_num'] = $item['couponReceiveNum'];
        $data['month_sales'] = $item['monthSales'];
        $data['coupon_start_time'] = $item['couponStartTime'];
        $data['coupon_end_time'] = $item['couponEndTime'];
        $data['coupon_price'] = $item['couponPrice'];
        $data['item_link'] = $item['itemLink'];
        $data['sub_cid'] = $item['subcid'];
        $data['tb_cid'] = $item['tbcid'];
        $data['coupon_conditions'] = $item['couponConditions'];
        $data['daily_sales'] = $item['dailySales'];
        $data['two_hours_sales'] = $item['twoHoursSales'];
        $data['cid'] = $item['cid'];
        $data['desc'] = $item['desc'];
        $data['activity_type'] = $item['activityType'];
        $data['activity_start_time'] = $item['activityStartTime'];
        $data['activity_end_time'] = $item['activityEndTime'];
        $data['hot_push'] = $item['hotPush'];
        $data['discount_full'] = $item['discountFull'];
        $data['discount_cut'] = $item['discountCut'];
        $data['seller_id'] = $item['sellerId'];
        $data['brand_id'] = $item['brandId'];
        $data['shop_type'] = $item['shopType'];
        if (!empty($item['specialText'])) {
            $data['special_text'] = implode(',', $item['specialText']);
        }
        return $data;
    }

    /**
     * 保存品牌
     *
     * @param $brandName
     * @param $brandId
     * @return mixed
     */
    private function saveBrand($brandName, $brandId)
    {
        $brand = $this->brandModel->where('name', $brandName)->find();
        if (!empty($brand) || is_null($brandName)) {
            return $brand['brand_id'];
        }
        $data['name'] = $brandName;
        $data['brand_id'] = $brandId;
        $this->brandModel->insert($data);
        return $brandId;
    }

    /**
     * 保存店铺
     *
     * @param $shopName
     * @param $sellerId
     * @param $shopType
     * @param $shopLogo
     * @param $shipScore
     * @param $serviceScore
     * @param $drsScore
     */
    private function saveShop($shopName, $sellerId, $shopType, $shopLogo, $shipScore, $serviceScore, $drsScore)
    {
        $shop = $this->shopModel->where('name', $shopName)->find();
        if (!empty($shop)) {
            return;
        }
        $data['name'] = $shopName;
        $data['seller_id'] = $sellerId;
        $data['type'] = $shopType;
        $data['logo'] = $shopLogo;
        $data['ship_score'] = $shipScore;
        $data['service_score'] = $serviceScore;
        $data['dsr_score'] = $drsScore;
        $this->shopModel->insert($data);
    }
}